
#include "sd2059.h"
#include "stdint.h"
#include "stdio.h"
#include "string.h"

#include "iic.h"

STR_SD2059_DATA RTC_time_default = {
    .type.second = 0x50,
    .type.minute = 0x38,
    .type.hour = 0x15,
	.type.base = 0x01,
    .type.week = 0x02,
    .type.day = 0x03,
    .type.month = 0x06,
    .type.year = 0x25
};

STR_SD2059_DATA RTC_realtime;


/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void sd2059_write_enable(void)
{
	
    iic_byte_write(I2C1, DEV_WR_ADDR, CTR2_ADDR, CTR2_BIT_WRTC1);
    iic_byte_write(I2C1, DEV_WR_ADDR, CTR1_ADDR, CTR1_BIT_WRTC2 | CTR1_BIT_WRTC3); 
	
}



/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void sd2059_write_disable(void)
{
	
    iic_byte_write(I2C1, DEV_WR_ADDR, CTR2_ADDR, 0x00);
    iic_byte_write(I2C1, DEV_WR_ADDR, CTR1_ADDR, 0x00); 		
	
}



/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void sd2059_realtime_set(STR_SD2059_DATA *time)
{
	uint8_t write_addr = 0;
	
	for(uint8_t i=0; i<7; i++)
	{
		iic_byte_write(I2C1, DEV_WR_ADDR, (write_addr + i), time->data[i]);
	}
}



/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void sd2059_init(void)
{	
    uint8_t ctr1;
    uint8_t ram0;
	
    iic_buffer_read(I2C1, &ctr1, DEV_RD_ADDR, CTR1_ADDR, 1);
    iic_buffer_read(I2C1, &ram0, DEV_RD_ADDR, RAM0_ADDR, 1);
	
    if ((ctr1 & CTR1_BIT_RTCF) || ram0 != 0xA7)
    {
        sd2059_write_enable();
        sd2059_realtime_set(&RTC_time_default);
		
        ram0 = 0xA7;
        iic_byte_write(I2C1, DEV_WR_ADDR, RAM0_ADDR, ram0);
        sd2059_write_disable();       
    }
	
    iic_buffer_read(I2C1, &RTC_realtime.data[0], DEV_RD_ADDR, 0, 7);	
}

/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void RTC_realtime_get(void)
{
	iic_buffer_read(I2C1, &RTC_realtime.data[0], DEV_RD_ADDR, 0, 7);
}



/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void RTC_realtime_set(uint8_t *time)
{
	STR_SD2059_DATA time_now;
	
	for(uint8_t i=0; i<7; i++)
	{
		time_now.data[i] = *(time + i);
	}
	
	time_now.type.base = 1;
	
	sd2059_realtime_set(&time_now);
	
}	














